<?php

declare (strict_types=1);
namespace App\Model;

use App\Constants\Constant;
use Carbon\Carbon;
use Hyperf\DbConnection\Model\Model;
/**
 * @property int $act_id 
 * @property string $act_name 
 * @property int $type 
 * @property string $type_content 
 * @property float $fee 
 * @property int $score 
 * @property string $score_content 
 * @property string $people_range 
 * @property string $address 
 * @property string $thumbnail 
 * @property string $introduce 
 * @property string $share_content 
 * @property int $is_show 
 * @property int $status 
 * @property string $add_time 
 */
class Activity extends Model
{
    /**
     * The table associated with the model.
     *
     * @var string
     */
    protected $table = 'activity';
    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    protected $fillable = ['act_name','type','type_content','fee','score','score_content','people_range','address','thumbnail','introduce','share_content'];
    /**
     * The attributes that should be cast to native types.
     *
     * @var array
     */
    protected $casts = ['act_id' => 'integer', 'type' => 'integer', 'type_content' => 'json', 'fee' => 'float', 'score' => 'integer', 'score_content' => 'json', 'share_content' => 'json', 'is_show' => 'integer', 'status' => 'integer'];

    public $timestamps = false;

    protected $primaryKey = "act_id";

    protected $appends = ['is_start','server_datetime'];

    public function getIsStartAttribute(){
        $is_start = false;
        if(Carbon::now()->gte($this->getAttribute("type_content")['start_time'])){
            $is_start = true;
        }
        if(isset($this->getAttribute("type_content")['end_time']) && !empty($this->getAttribute("type_content")['end_time']) && Carbon::now()->gte($this->getAttribute("type_content")['end_time'])){
            $this->status = Constant::ACTIVITY_STATUS_FINISH;
            $this->save();
            $is_start = false;
        }
        return $this->status == Constant::ACTIVITY_STATUS_NORMAL && $is_start;
    }

    public function getServerDateTimeAttribute(){
        return Carbon::now()->toDateTimeString();
    }

    public function payments(){
        return $this->hasMany(Payment::class,'source_id','act_id')->where("origin",Constant::ORIGIN_ACTIVITY);
    }

    public function resources(){
        return $this->hasMany(Resource::class,'source_id','act_id')->where("origin",Constant::ORIGIN_ACTIVITY);
    }

    public function users(){
        return $this->belongsToMany(User::class,'activity_user_mid','act_id','user_id');
    }
}